import React, { Key, useRef, useState } from 'react';
import { GCrudTable, GIcon } from 'geminis-react';
import { Button, Divider, message, Upload } from 'antd';
import styles from '../category/components/tree.less';
import { CagegoryTree } from '@/pages/everydata/category/components/tree';
import { Move } from '@/pages/everydata/table/components/move/move';

export default () => {
  const table = useRef<any>();
  const tree = useRef<any>();
  const [tableSelection, setTableSelection] = useState<{
    selectedKeys: React.Key[];
    selectedRows: any[];
  }>();
  const [treeSelection, setTreeSelection] = useState<Key[]>();

  const buttons = ['add', 'edit', 'delete', 'refresh'];

  const onTreeSelect = (selectedKeys: Key[]) => {
    table.current.loadData({
      filters: [
        {
          field: 'category.id',
          compareType: selectedKeys[0] === '' ? 'is null' : '=',
          value: selectedKeys[0],
        },
      ],
    });
    setTreeSelection(selectedKeys);
  };

  const tableSchema = {
    title: '表格信息',
    table: {
      schema: {
        data: {
          autoload: false,
          url: '/api/everydata/tables',
        },
      },
      schemaPath: '/everydata-pc/schemas/table/table.json',
    },
    add: {
      button: {
        modal: {
          width: '800px',
        },
      },
      form: {
        schema: {
          data: {
            url: '/api/everydata/tables',
          },
        },
        schemaPath: '/everydata-pc/schemas/table/edit.json',
        onDataLoaded: (value: any) => {
          if (
            value.schemaData.table.schema.data.url.indexOf(
              '/api/everydata/data/',
            ) === 0
          ) {
            value.schemaData.table.schema.data.url =
              value.schemaData.table.schema.data.url.substring(20);
            value.schemaData.table.schema.rowKey = '_id';
            value.schemaData.dataType = 'gemini';
          }
          value.schemaData.buttons = [];
          buttons.forEach((button) => {
            if (value.schemaData[button] !== false) {
              value.schemaData.buttons.push(button);
            }
          });
        },
        onSubmitting: (schema: any, value: any) => {
          const categoryId = tree.current.selection.selectedKeys[0];
          if (!value.category) {
            value.category = {};
          }
          value.category.id = categoryId === '' ? null : categoryId;
          value.name = value.schemaData.title;
          if (value.schemaData.dataType === 'gemini') {
            value.schemaData.table.schema.data.url =
              '/api/everydata/data/' + value.schemaData.table.schema.data.url;
          }
          delete value.schemaData.dataType;
          buttons.forEach((button) => {
            if (value.schemaData.buttons.indexOf(button) > -1) {
              delete value.schemaData[button];
            } else {
              value.schemaData[button] = false;
            }
          });
          delete value.schemaData.buttons;
          return value;
        },
      },
    },
  };

  return (
    <div className={styles.main}>
      <div className={styles.tree}>
        <CagegoryTree ref={tree} onSelect={onTreeSelect} />
      </div>
      <Divider type="vertical" className={styles.fullHeight} />
      <div className={styles.content}>
        <GCrudTable
          ref={table}
          schema={tableSchema}
          onSelected={setTableSelection}
          external={{
            pos2: (
              <>
                <Button
                  disabled={tableSelection?.selectedKeys?.length !== 1}
                  icon={<GIcon type="icon-visible" />}
                  href={'table/view?id=' + tableSelection?.selectedKeys[0]}
                  target="blank"
                >
                  查看
                </Button>
                <Move
                  id={tableSelection?.selectedKeys[0]?.toString()}
                  disabled={tableSelection?.selectedKeys?.length !== 1}
                  onOk={() => {
                    table.current.loadData();
                  }}
                />
              </>
            ),
            pos3: (
              <>
                <Button
                  icon={<GIcon type="icon-download" />}
                  disabled={tableSelection?.selectedKeys.length !== 1}
                  onClick={() => {
                    window.open(
                      '/api/everydata/tables/' +
                        tableSelection?.selectedKeys[0] +
                        '/export',
                    );
                  }}
                >
                  导出
                </Button>
                <Upload
                  showUploadList={false}
                  action={
                    '/api/everydata/tables/import/' +
                    treeSelection?.[0]?.toString()
                  }
                  onChange={(info) => {
                    if (info.file.status === 'done') {
                      message.success('成功');
                      table.current.loadData();
                    } else if (info.file.status === 'error') {
                      message.error('失败');
                    }
                  }}
                >
                  <Button icon={<GIcon type="icon-upload" />}>导入</Button>
                </Upload>
              </>
            ),
          }}
        />
      </div>
    </div>
  );
};
